package com.oa.pm.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.joneying.common.annotation.CommonService;
import com.joneying.common.web.response.Resp;
import com.oa.admin.entity.Holiday;
import com.oa.admin.entity.UserHoliday;
import com.oa.admin.service.IHolidayService;
import com.oa.admin.service.IUserHolidayService;
import com.oa.core.PageResult;
import com.oa.core.enumm.ProcessDefineEnum;
import com.oa.core.exception.BusinessException;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.core.utils.DateUtil;
import com.oa.core.utils.ExcelUtil;
import com.oa.pm.dto.EntryInformationAddDTO;
import com.oa.pm.dto.EntryInformationAuditDTO;
import com.oa.pm.dto.EntryInformationListDTO;
import com.oa.pm.entity.*;
import com.oa.pm.mapper.EntryInformationMapper;
import com.oa.pm.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.oa.pm.vo.EntryInformationListVO;
import com.oa.pm.vo.EntryInformationVO;
import com.oa.system.dto.ApplyApprovalAddDTO;
import com.oa.system.dto.ApprovalDTO;
import com.oa.system.entity.*;
import com.oa.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 入职信息表(个人资料表) 服务实现类
 * </p>
 *
 * @author syb123
 * @since 2019-01-22
 */
@Service
public class EntryInformationServiceImpl extends ServiceImpl<EntryInformationMapper, EntryInformation> implements IEntryInformationService {

    private final EntryInformationMapper entryInformationMapper;

    @Autowired
    private IOccupationalHistoryService occupationalHistoryService;

    @Autowired
    private ILearningExperienceService learningExperienceService;

    @Autowired
    private ILearningExperienceFileService learningExperienceFileService;

    @Autowired
    private IFamilyInformationService familyInformationService;

    @Autowired
    private IApplyApprovalService applyApprovalService;

    @Autowired
    private IHolidayService holidayService;

    @Autowired
    private IUserHolidayService userHolidayService;

    @Autowired
    private IUserService userService;

    @Autowired
    public EntryInformationServiceImpl(EntryInformationMapper entryInformationMapper) {
        this.entryInformationMapper = entryInformationMapper;
    }

    @CommonService
    @Override
    public EntryInformationVO findEntryInformation(String id, String userId) {
        return entryInformationMapper.findEntryInformation(id, userId);
    }

    @CommonService
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Resp addEntryInformation(EntryInformationAddDTO entryInformationAddDTO) throws BusinessException, DataIsEmptyException {
        List<EntryInformation> entryInformations= entryInformationMapper.selectList(new EntityWrapper().eq("is_deleted", 2).eq("user_id", entryInformationAddDTO.getUserId()));
        if(entryInformations.size() > 0) {
            return new Resp().failure("已有入职申请提交记录了");
        }

        EntryInformation entryInformation = new EntryInformation();
        BeanUtils.copyProperties(entryInformationAddDTO, entryInformation);

        if(insert(entryInformation)){
            if(entryInformationAddDTO.getOccupationalHistoryAddDTOS() != null && entryInformationAddDTO.getOccupationalHistoryAddDTOS().size() > 0){
                List<OccupationalHistory> occupationalHistories = new ArrayList<>();
                entryInformationAddDTO.getOccupationalHistoryAddDTOS().forEach(d -> {
                    OccupationalHistory occupationalHistory = new OccupationalHistory();
                    BeanUtils.copyProperties(d, occupationalHistory);
                    occupationalHistory.setEntryInfomationId(entryInformation.getId());
                    occupationalHistories.add(occupationalHistory);
                });
                occupationalHistoryService.insertBatch(occupationalHistories);
            }

            if(entryInformationAddDTO.getLearningExperienceAddDTOS()!= null && entryInformationAddDTO.getLearningExperienceAddDTOS().size() > 0){
                entryInformationAddDTO.getLearningExperienceAddDTOS().forEach(d -> {
                    LearningExperience learningExperience = new LearningExperience();
                    BeanUtils.copyProperties(d, learningExperience);
                    learningExperience.setEntryInfomationId(entryInformation.getId());
                    if(learningExperienceService.insert(learningExperience)){
                        List<LearningExperienceFile> learningExperienceFiles = new ArrayList<>();
                        if(d.getLearningExperienceFileAddDTOS() != null && d.getLearningExperienceFileAddDTOS().size() > 0) {
                            d.getLearningExperienceFileAddDTOS().forEach(s -> {
                                LearningExperienceFile learningExperienceFile = new LearningExperienceFile();
                                BeanUtils.copyProperties(s, learningExperienceFile);
                                learningExperienceFile.setLearningExperienceId(learningExperience.getId());
                                learningExperienceFiles.add(learningExperienceFile);
                            });
                            learningExperienceFileService.insertBatch(learningExperienceFiles);
                        }
                    }
                });
            }


            if(entryInformationAddDTO.getFamilyInformationAddDTOS() != null && entryInformationAddDTO.getFamilyInformationAddDTOS().size()> 0){
                List<FamilyInformation> familyInformations = new ArrayList<>();
                entryInformationAddDTO.getFamilyInformationAddDTOS().forEach(d -> {
                    FamilyInformation familyInformation = new FamilyInformation();
                    BeanUtils.copyProperties(d, familyInformation);
                    familyInformation.setEntryInformationId(entryInformation.getId());
                    familyInformations.add(familyInformation);
                });
                familyInformationService.insertBatch(familyInformations);
            }
            ApplyApprovalAddDTO applyApprovalAddDTO = new ApplyApprovalAddDTO();
            applyApprovalAddDTO.setApplyId(entryInformation.getId());
            applyApprovalAddDTO.setApprovalProcessId(ProcessDefineEnum.ENTRY.getId());
            applyApprovalAddDTO.setApplyApprovalName(entryInformation.getName() + ProcessDefineEnum.ENTRY.getText());
            applyApprovalAddDTO.setApprovalUserId(entryInformation.getUserId());
            return applyApprovalService.addApproval(applyApprovalAddDTO);
        }
        throw new BusinessException("提交申请失败!");
    }

    @CommonService
    @Override
    public PageResult<EntryInformationListVO> findEntryInformationList(EntryInformationListDTO entryInformationListDTO) {
        return new PageResult<>(entryInformationMapper.findEntryInformationList(entryInformationListDTO.getPage(), entryInformationListDTO), entryInformationListDTO.getPage().getPages());
    }

    @Transactional(rollbackFor = Exception.class)
    @CommonService
    @Override
    public Resp audit(EntryInformationAuditDTO entryInformationAuditDTO) throws DataIsEmptyException, BusinessException {
        ApprovalDTO approvalDTO = new ApprovalDTO();
        approvalDTO.setId(Long.valueOf(entryInformationAuditDTO.getApplyApprovalId()));
        approvalDTO.setUserId("1");
        approvalDTO.setStatus(entryInformationAuditDTO.getAuditStatus());
        return applyApprovalService.audit(approvalDTO, x -> {
            if(x.getStatus() == 1){
                return;
            }
            if(!x.isLastStatus()){
                return;
            }

            EntryInformation entryInformation = new EntryInformation();
            entryInformation.setId(entryInformationAuditDTO.getId());
            entryInformation.setSeniority(entryInformationAuditDTO.getSeniority());
            entryInformation.setLengthOfServiceAnnualLeave(entryInformationAuditDTO.getLengthOfServiceAnnualLeave());
            if(updateById(entryInformation)) {
                EntryInformation entryInformation1 = entryInformationMapper.selectById(entryInformationAuditDTO.getId());

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                String year = sdf.format(new Date());
                Integer ranking = userService.findRanking(entryInformation1.getUserId(), year);
                User user = new User();
                user.setId(entryInformation1.getUserId());
                user.setJobNo(entryInformationAuditDTO.getJobNoPrefix() + year + ranking);
                userService.updateById(user);

                String userId = entryInformationMapper.selectById(entryInformationAuditDTO.getId()).getUserId();

                List<Holiday> holidays = holidayService.selectList(new EntityWrapper<>());
                List<UserHoliday> userHolidays = userHolidayService.selectList(new EntityWrapper().eq("user_id", userId));

                if (userHolidays != null && userHolidays.size() > 0) {
                    userHolidayService.delete(new EntityWrapper().eq("user_id", userId));
                } else {
                    userHolidays = new ArrayList<>();
                }

                for (Holiday d : holidays) {
                    UserHoliday userHoliday = new UserHoliday();
                    userHoliday.setHolidayId(d.getId());
                    userHoliday.setUserId(userId);
                    userHoliday.setAlreadyUsedDay(0.0);
                    userHoliday.setSurplusDay(d.getHolidayNumber());
                    if (d.getId() == 21) {
                        userHoliday.setSurplusDay(Double.valueOf(entryInformation.getLengthOfServiceAnnualLeave()));
                    }
                    userHolidays.add(userHoliday);
                }
                userHolidayService.insertBatch(userHolidays);
            }
        });
    }

    @Override
    public void export(EntryInformationListDTO entryInformationListDTO, HttpServletResponse response) {
        List<EntryInformationListVO> entryInformationList = entryInformationMapper.findEntryInformationList(new Page(), entryInformationListDTO);
        String[] rows = {"ID", "申请ID", "用户姓名", "部门", "性别", "岗位", "职务", "劳动合同到期时间", "", "审核状态", "节点ID"};
        try {
            ExcelUtil.downloadExcel("入职信息列表" + DateUtil.getDayMonth(), rows, entryInformationList, "入职信息列表" + DateUtil.getDayMonth()+".xls", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
